package com.googlecode.totallylazy.reducers;

import com.googlecode.totallylazy.Predicate;
import com.googlecode.totallylazy.predicates.LogicalPredicate;

import java.util.Collection;
import java.util.concurrent.Callable;

public class CollectionFilter<T, C extends Collection<T>> extends CollectionReducer<T, T, C> {
    private final LogicalPredicate<T> predicate;

    public CollectionFilter(Predicate<? super T> predicate, Callable<? extends C> identity) {
        super(identity);
        this.predicate = LogicalPredicate.logicalPredicate(predicate);
    }

    @Override
    public C call(C collection, T t) throws Exception {
        if (predicate.matches(t)) collection.add(t);
        return collection;
    }
}
